import { ref, reactive, watch } from 'vue'
import { items } from '@/testData/menu'
import { router } from '@/router'

import { flatten } from '@/utils/common'
const _items = flatten(items);

import { useMain } from '@/store/store';
const mainStore = useMain();

import { storeToRefs } from 'pinia'
const { tagListStore } = storeToRefs(useMain())

export const tagList = ref([{
    title: '首页',
    url: '/admin/index'
}])

/**
 * 菜单状态
 */
export const state = reactive({
    collapsed: false,
    selectedKeys: ['/admin/index'],
    openKeys: ['首页'],
    preOpenKeys: ['首页'],
});

/**
 * 监控路由变化
 */
watch(
    () => state.selectedKeys,
    (_val: string[]) => {
        console.log(_val[0])
        _items.forEach(element => {
            if (state.selectedKeys[0] === element.key) {
                state.openKeys[0] = element.title
                state.preOpenKeys[0] = element.title
            }
        });
    }
);

/**
 * 初始化当前打开项
 */
_items.forEach(element => {
    if (window.location.pathname === element.key) {
        state.selectedKeys[0] = element.key
        state.openKeys[0] = element.title
        state.preOpenKeys[0] = element.title
    }
});

/**
 * 加载页面的时候判断store里面是否有tagList数据
 *      如果有将仓库里面的放入tagList中
 *      否则不做处理
 */
if (tagListStore.value && tagListStore.value.length > 0) {
    tagList.value = tagListStore.value
}

/**
 * 菜单跳转
 */
export const toView = () => {
    setTimeout(() => {
        router.push({
            path: state.selectedKeys[0]
        })
        _items.forEach(element => {
            if (state.selectedKeys[0] === element.key) {
                for (let i = 0; i < tagList.value.length; i++) {
                    if (tagList.value[i].url === state.selectedKeys[0]) {
                        return;
                    }
                }
                tagList.value.push({
                    title: element.title,
                    url: state.selectedKeys[0]
                })
                mainStore.tagListStore = tagList.value;
            }
        });
    }, 0);
}

/**
 * 切换tab
 */
export const checkTab = (val: { url: string; }) => {
    router.push({
        path: val.url
    })
    state.selectedKeys[0] = val.url
}

/**
 * 关闭菜单
 */
export const closeTag = (val: string, index: number) => {
    if (val !== '/admin/index') {
        tagList.value.splice(index, 1);
        mainStore.tagListStore = tagList.value;
        // 如果关闭的是当前
        if (val === state.selectedKeys[0]) {
            // 判断当前项是否是最后一项
            // 如果是最后一项，加载前面一项
            if (index === tagList.value.length) {
                checkTab(tagList.value[index - 1])
            } else {
                // 如果不是最后一项，加载最后一项
                checkTab(tagList.value[index])
            }
        }
    }
}
